﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Model;
using BllFactory;
using IBLL;
using ETWebApi2.Models;
using System.Web;
using System.Text;
using System.Configuration;
using Jose;

namespace ETWebApi2.Controllers
{
    [Route("etcad")]
    public class ETCADLoginController : ApiController
    {
        private ICustomers_tbService m_cusService = ServiceFactory.CreatService<ICustomers_tbService>();
        private ICUser_tbService m_userService = ServiceFactory.CreatService<ICUser_tbService>();
        private ILocks_tbService m_lockService = ServiceFactory.CreatService<ILocks_tbService>();

        //在CAD中点击登录时候的判断
        [HttpGet]
        public HttpResponseMessage GetLogin(string lockinnum, string mac)
        {
            HttpResponseMessage hrm = new HttpResponseMessage();
            if(string.IsNullOrEmpty(lockinnum) || string.IsNullOrEmpty(mac))
                return hrm = ObjectToJson.toJson(new { status = 201, error = "无法检测到锁信息和MAC,视为客户" });
            else
            {
                if (lockinnum.Length > 15 || mac.Length != 12)
                    return hrm = ObjectToJson.toJson(new { status = 201, error = "锁号："+lockinnum+"，Mac:"+mac+",信息错误" });
                else                
                {
                    Customers_tb cus = GetCustomers(lockinnum);
                    if(cus==null)//验证合法身份
                        return hrm = ObjectToJson.toJson(new { status = 201, error = "找不到锁号'"+lockinnum+"'相应的客户信息" });
                    else
                    {
                        if (cus.IsDeal > 10)
                            return LoginsAuto(mac, lockinnum, cus.Name); //有权进入外发
                        else
                            return hrm = ObjectToJson.toJson(new { status = 201, error = "公司"+cus.Name+"无权进入外发系统" });
                    }
                }
            }
        }

        //ETCAD中MAC自动登录本系统  （本机登录） 跳转到MyFiles.aspx(我的上传)界面       
        private HttpResponseMessage LoginsAuto(string mac, string lockinnum, string companyName)
        {
            HttpResponseMessage message = new HttpResponseMessage();
            message = ObjectToJson.toJson(new { status = 201, error = "信息有误" });
            if (lockinnum != null && mac != null)
            {
                if (lockinnum.Length <= 15 && mac.Length == 12)
                {
                    Customers_tb cus = GetCustomers(lockinnum);
                    if (cus != null)
                    {
                        CUser_tb user = m_userService.GetList(u => u.CompanyId == cus.Id && u.MAC == mac).FirstOrDefault();
                        if (user != null && user.CompanyId == cus.Id)
                        {
                            if (user.State == 1)
                            {
                                HttpContext.Current.Session["LockInnum"] = lockinnum; //用于验证权限
                                var secret = ConfigurationManager.AppSettings["secret"];
                                JwtAuthObject payload = new JwtAuthObject()
                                {
                                    UserId = user.Id,
                                    CurentCopmpanyId = user.CompanyId
                                };
                                //生成 token  
                                string token = JWT.Encode(payload, Encoding.UTF8.GetBytes(secret), JwsAlgorithm.HS256);
                                HttpContext.Current.Session["UserInfo"] = payload;
                                if (new BaseClass().isHaveUploadPage(lockinnum, user))
                                    message = ObjectToJson.toJson(new { status = 200, rel = true, companyName = companyName,token= token,username = user.UserName }); //有上传权限
                                else
                                    message = ObjectToJson.toJson(new { status = 201, error = "没有上传权限", companyName = companyName, token = token,username=user.UserName });//没有上传权限
                            }
                            else
                                message = ObjectToJson.toJson(new { status = 201, error = "主管还没有认证", companyName = companyName}); //主管还没有认证        
                        }
                        else
                            message = ObjectToJson.toJson(new { status = 201, error = "这台电脑还没有在系统内注册,请填写您的姓名,并点击注册 ", companyName = companyName });// 这台电脑还没有在系统内注册,请填写您的姓名,并点击注册                             
                    }
                }
            }
            return message;
        }

        // POST: api/ETCADLogin
        /// <summary>
        /// ETCAD注册  提供参数  username phone locknum mac
        /// </summary>
        /// <param name="obj"></param>
        [HttpPost]
        public HttpResponseMessage PostRegister()
        {
            //生成随机六位数密码
            Random r = new Random();
            //初始密码  
            string m_initialPwd = r.Next(100000, 999999).ToString();
            HttpContext context = HttpContext.Current;
            string userName = context.Request.Params["username"];
            string phone = context.Request.Params["phone"];
            string locknum = context.Request.Params["locknum"];
            string inputMac = context.Request.Params["mac"];
            string email = context.Request.Params["email"];
            string MAC = inputMac.Split(',').Last();
            Customers_tb cus = GetCustomers(locknum);
            if (cus == null)
                return ObjectToJson.toJson(new { status = 201, error = "该锁不合法" });
            //当前锁所在的公司是否已有当前注册用户
            CUser_tb user = m_userService.GetList(u => u.CompanyId == cus.Id && (u.MAC == MAC || u.UserName ==userName)).FirstOrDefault();
            if (user == null) //说明在本公司没有当前名称的用户
            {
                    if (!string.IsNullOrEmpty(phone))
                    {
                        CUser_tb isuser = m_userService.GetList(u => u.Phone == phone.Replace(" ", "")).FirstOrDefault();
                        if (isuser == null)
                            return AddUser(cus.Id, userName, m_initialPwd, phone, MAC, email);
                        else
                            return ObjectToJson.toJson(new { status = 201, error = "该账号已经存在公司:" + new BaseClass().GetCompanyName(isuser.CompanyId) + ",请换重新注册,或者联系主管恢复您的权限" });//  this.PageSkip("该账号已经存在,请换一个名字重新注册,或者联系主管恢复您的权限", "Login", "locknum=" + locknum);
                    }else
                        return AddUser(cus.Id, userName, m_initialPwd, "", MAC, email);
            }        
            else
            {
                if (userName.Equals(user.UserName))
                    return ObjectToJson.toJson(new { status = 201, error = cus.Name + "在本公司已存在该名称无法注册 ,建议重命名" });
                return ObjectToJson.toJson(new { status = 201, error = "该主机已经绑定用户:" + user.UserName + ", 请联系主管, 将该员工的mac地址清空之后, 您再注册" }); //    this.PageSkip("该主机已经绑定用户:" + user.UserName + ",请联系主管,将该员工的mac地址清空之后,您再注册", "Login", "locknum=" + locknum);
            }
        }

        private HttpResponseMessage AddUser(int id,string userName, string m_initialPwd, string phone, string MAC,string email )
        {
            CUser_tb cUser = new CUser_tb(id, userName, m_initialPwd, phone, MAC, "版师", email);
            if (m_userService.Add(cUser))
                return ObjectToJson.toJson(new { status = 200, rel = true });//  this.PageSkip("注册成功，请联系主管激活该账号后可登陆系统！", "Login", "locknum=" + locknum);
            else
                return ObjectToJson.toJson(new { status = 201, error = "注册失败" });
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="LockInNum">锁的编号</param>
        /// <returns></returns>
        private Customers_tb GetCustomers(string LockInNum)
        {
            if (!string.IsNullOrEmpty(LockInNum))
            {
                Locks_tb sItem = m_lockService.GetList(l => l.lockInsideNum == LockInNum).FirstOrDefault();
                if (sItem != null && sItem.lstate != 3)//锁存在且没有被废弃
                {
                    Customers_tb cItem = m_cusService.GetList(c => c.Id == sItem.customerId).FirstOrDefault();
                    if (cItem != null)//目前只考虑此客户确实存在即可 （该客户能与哪些其他客户交换文件以后再完善）
                    {
                        return cItem;
                    }
                }
            }
            return null;
        }
    }
}
